package com.qiall.ali;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.CreateLiveChannelRequest;
import com.aliyun.oss.model.CreateLiveChannelResult;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.net.URL;
import java.util.Date;

/**
 * 阿里云oss 工具
 */
public class Oss {

    private static String endpoint = "oss-cn-beijing.aliyuncs.com";

    private final static String CHARSET_UTF8 = "utf8";
    private final static String ALGORITHM = "HmacSHA1";

    private OSS ossClient;

    public OSS getOssClient() {
        return ossClient;
    }

    public void init(String accessKeyId, String accessKeySecret) {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

    }

    public void upload(String bucketName, InputStream inputStream, String objectName) {
        ossClient.putObject(bucketName, objectName, inputStream);
        ossClient.shutdown();
    }

    public void deleteObject(String bucketName, String objectName) {
        ossClient.deleteObject(bucketName, objectName);
    }

    public void deleteBucket(String bucketName) {
        ossClient.deleteBucket(bucketName);
    }

    public String getTmpUrl(String bucketName, String objName) {
        if (ossClient == null) {
        }
        return ossClient.generatePresignedUrl(bucketName, objName, new Date(System.currentTimeMillis() + 3600000), HttpMethod.GET).toString();
    }

    /**
     * 定制逻辑只有华北2区域可以用
     *
     * @param bucketName
     * @param objName
     * @return
     */
    public String getPublicUrl(String bucketName, String objName) {
        String url = "http://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + objName;
        return url;
    }

    public void createBucket(String bucketName) {
        ossClient.createBucket(bucketName);
    }


    public void shutDown() {
        ossClient.shutdown();
    }

    public String getTmpUrl(String bucketName, String objectName, Long timeOUt) {
        Date expiration = new Date(System.currentTimeMillis() + timeOUt);
        // 生成以GET方法访问的签名URL，访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        return url.toString();
    }


}
